<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Illuminate\Support\Facades\Log;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Illuminate\Support\Facades\Redis;

class GetUserFromToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next,$role="lawyer")
    {
        // wps传的特殊形式token
        if ($token = $request->header('x-wps-weboffice-token')) {
            $request->headers->set('Authorization','Bearer '.$token);
        }
        $newToken = null;
        if (! $token = JWTAuth::setRequest($request)->getToken()) {
            return response()->json([
                'code' => '2',
                'msg' => '该功能需登录后才能访问呢~',
                'data' => '',
            ]);
        }
        $auth = JWTAuth::parseToken();

        try {
            $user = $auth->authenticate($token);
            // 查询是否被冻结账号
            $frozenUid = $role=='admin'?false : Redis::exists('frozenIds:'.hashid_encode($user->id));
            if (! $user || $frozenUid) {
                return response()->json([
                    'code' => '2',
                    'msg' => '账号或被冻结，请退出重新登录试试',
                    'data' => '',
                ]);
            }
            $request->headers->set('Authorization','Bearer '.$token);
        } catch (TokenExpiredException $e) {
            try {
                // 刷新token,超时刷新将会去catch
                $refresh = JWTAuth::parseToken()->refresh();
                // redis记住登录的用户
                $user = $auth->authenticate($refresh);
                $newToken = JWTAuth::fromUser($user);
                // 查询是否被冻结账号
                $frozenUid = $role=='admin'?false : Redis::exists('frozenIds:'.hashid_encode($user->id));
                if ($frozenUid) {
                    return response()->json([
                        'code' => '2',
                        'msg' => '账号或被冻结，请退出重新登录试试',
                        'data' => '',
                    ]);
                }
                // 给当前的请求设置性的token,以备在本次请求中需要调用用户信息
                $request->headers->set('Authorization','Bearer '.$newToken);
                // 存储登录日志
                Redis::sadd('log:login:'.strtotime(date('Y-m-d')),$user->id);
            } catch (JWTException $e) {
                // 账号过期
                return response()->json([
                    'code' => '2',
                    'msg' => '账号信息过期了，请重新登录',
                ]);
            }
        } catch (JWTException $e) {
            return response()->json([
                'code' => '2',
                'msg' => '请登录账号！',
                'data' => '',
             ]);
        }
        $response = $next($request);

        if (!empty($newToken)) {
            // 返回的响应头带上新token给前端存储
            $response->headers->set('Authorization', 'Bearer '.$newToken);
        }

        return $response;
    }
}
